package dhm.com.hpx.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.entity.LoginBean;
import dhm.com.hpx.utils.GetDeviceid;
import dhm.com.hpx.utils.SpUtils;
import dhm.com.hpx.utils.StringUtils;

public class LoginActivity extends BaseActivity implements LoginContract.IView {

    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.pass)
    EditText pass;
    @BindView(R.id.tishi)
    TextView tishi;
    @BindView(R.id.agree)
    CheckBox agree;

    private Drawable drawables;


    private PressenterImpl pressenter;
    private LoginBean loginBean;
    private String firstcom;

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView() {
        ButterKnife.bind(this);
        pressenter = new PressenterImpl();
        pressenter.attachView(this);

        String uid = SpUtils.getString(this, "uid");
        if (uid != null && !uid.equals("")) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        pass.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                // et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
                Drawable drawable = pass.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null) {
                    return false;
                }
                //如果不是按下事件，不再处理
                if (motionEvent.getAction() != MotionEvent.ACTION_UP) {
                    return false;
                }
                if (motionEvent.getX() > pass.getWidth() - pass.getPaddingRight() - drawable.getIntrinsicWidth()) {
                    showOrHide(pass);
                }
                return false;
            }
        });

    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.login, R.id.foeget, R.id.regist, R.id.xieyi, R.id.yinsi})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.login:

                String text_phone = phone.getText().toString();
                String text_pass = pass.getText().toString();

                if (text_phone == null || text_phone.equals("") || text_pass == null || text_pass.equals("")) {
                    Toast.makeText(this, "请检查数据", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (StringUtils.isRegistMobileNO(text_phone)) {
                    Toast.makeText(this, "手机号格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (StringUtils.isRegistMobileNO1(text_pass)) {
                    Toast.makeText(this, "密码格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!agree.isChecked()){
                    Toast.makeText(this, "请阅读并同意采客宝用户协议和隐私政策", Toast.LENGTH_SHORT).show();
                    return;
                }
                Map<String, String> map = new HashMap<>();
                map.put("user_login", text_phone);
                map.put("user_pass", text_pass);
                map.put("token", Constant.TOKEN);

                pressenter.sendMessage(this, Constant.login, map, LoginBean.class);
                break;
            case R.id.foeget:
                intent = new Intent(this, ForgetActivity.class);
                startActivity(intent);
                break;
            case R.id.regist:
                intent = new Intent(this, RegistActivity.class);
                startActivity(intent);
                break;
            case R.id.xieyi:
                intent = new Intent(this, WebActivity.class);
                intent.putExtra("type","1");
                startActivity(intent);
                break;
            case R.id.yinsi:
                intent = new Intent(this, WebActivity.class);
                intent.putExtra("type","2");
                startActivity(intent);
                break;
            default:
        }
    }

    int isfirst=0;
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);


        firstcom = SpUtils.getString(this, "firstcom");

        if (isfirst==0){
            if (firstcom == null || firstcom.equals("")) {
                showPopwindow();
                isfirst=1;
            }
        }

    }

    private void showOrHide(EditText etPassword) {
        //记住光标开始的位置
        int pos = etPassword.getSelectionStart();
        if (etPassword.getInputType() != (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)) {//隐藏密码
            drawables = getResources().getDrawable(R.mipmap.eyen);
            drawables.setBounds(0, 0, drawables.getMinimumWidth(), drawables.getMinimumHeight());
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else {//显示密码
            drawables = getResources().getDrawable(R.mipmap.eyes);
            drawables.setBounds(0, 0, drawables.getMinimumWidth(), drawables.getMinimumHeight());
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }
        etPassword.setCompoundDrawablesWithIntrinsicBounds(null, null, drawables, null);
        etPassword.setSelection(pos);
    }

    @Override
    public void requesta(Object data) {

        if (data instanceof LoginBean) {
            loginBean = (LoginBean) data;
            if (loginBean.getCode() == 1) {

                if ((isfirst==1)||(loginBean.getData().getEquipment()==null|| loginBean.getData().getEquipment().equals("")|| loginBean.getData().getEquipment().equals("null"))){

                    Map<String,String> map=new HashMap<>();
                    map.put("token",Constant.TOKEN);
                    map.put("uid", loginBean.getData().getUid()+"");
                    map.put("equipment",GetDeviceid.id(this));

                    pressenter.sendMessage(LoginActivity.this,Constant.binding_equiment,map, Bean.class);

                }else {
                    Map<String,String> map=new HashMap<>();
                    map.put("token",Constant.TOKEN);
                    map.put("uid", loginBean.getData().getUid()+"");
                    map.put("equipment",GetDeviceid.id(this));

                    pressenter.sendMessage(LoginActivity.this,Constant.matching_equiment,map, Bean.class);
                }
               /* Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();*/
            }else {
                Toast.makeText(this, loginBean.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }else if (data instanceof Bean){
            Bean bean= (Bean) data;
            if (bean.getCode()==1){
                SpUtils.saveString(this, "uid", loginBean.getData().getUid() + "");
                SpUtils.saveString(this, "myReferralCode", loginBean.getData().getMyReferralCode() + "");
                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
            }else {
                Toast.makeText(this, bean.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

    }

    @Override
    public void fail(String error) {
        Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
    }


    private PopupWindow popWindow;

    private void showPopwindow() {
        View popView = View.inflate(this, R.layout.first, null);
        TextView cancle = popView.findViewById(R.id.cancle);
        TextView sure = popView.findViewById(R.id.sure);
        TextView title = popView.findViewById(R.id.title);
        String itemStr = title.getText().toString();
        String xieyi = "《用户协议》";
        String yinsi = "《隐私政策》";

        int indexXieyi= itemStr.indexOf(xieyi);
        int indexYinsi= itemStr.indexOf(yinsi);
        SpannableString spannableString = new SpannableString(itemStr);

        //Service Terms 颜色和点击事件
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, WebActivity.class);
                intent.putExtra("type","1");
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(getResources().getColor(R.color.main));
                ds.setUnderlineText(true);
            }
        }, indexXieyi, indexXieyi + xieyi.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


        //Service Terms 颜色和点击事件
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, WebActivity.class);
                intent.putExtra("type","2");
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(getResources().getColor(R.color.main));
                ds.setUnderlineText(true);
            }
        }, indexYinsi, indexYinsi+ yinsi.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        title.setText(spannableString);
        title.setMovementMethod(LinkMovementMethod.getInstance());

/*

        SpannableString courseSpannablexieyi = new SpannableString(xieyi);
        SpannableString courseSpannableyinsi = new SpannableString(yinsi);

        RecordClickSpan courseSpanxieyi = new RecordClickSpan() {
            @Override
            public void onClick(View widget) {
            }
        };
        RecordClickSpan courseSpanyinsi = new RecordClickSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(LoginActivity.this, WebActivity.class);
                intent.putExtra("type","2");
                startActivity(intent);
            }
        };

        courseSpannablexieyi.setSpan(courseSpanxieyi, 0, xieyi.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        courseSpannableyinsi.setSpan(courseSpanyinsi, 0, yinsi.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        title.append("请你务必审慎阅读、充分理解《服务协议》和《隐私政策》各条款，包括但不限于:为了向你提供寻找采客宝、内容分享等服务，我们需要收集你的设备信息、操作日志等个人信息。你可以在'设置'中查看、变更、删除个人信息并管理你的授权。你可阅读");
        title.append(courseSpannablexieyi);
        title.append("和");
        title.append(courseSpannableyinsi);
        title.append("了解详细信息。如你同意，请点击'同意'开始接受我们的服务。");
*/

        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SpUtils.saveString(LoginActivity.this,"firstcom","1");
                popWindow.dismiss();

            }
        });

        popWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,true);
        popWindow.setFocusable(false);
        popWindow.setTouchable(true);
        popWindow.setOutsideTouchable(false);
//        popWindow.setAttachedInDecor(true);


        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                if (!popWindow.isShowing()){
                    setBackgroundAlpha(1.0f);
                }
            }
        });

        setBackgroundAlpha(0.5f);
        popWindow.showAtLocation(agree, Gravity.CENTER, 0, 0);

    }


    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }



}
